package UI;



import action.UserAction;

import javax.swing.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.*;
import java.sql.*;
import java.util.HashSet;
import java.util.Set;


/**(41)
 * 这是一个搜索界面,其中有输入框，搜索按钮，查询后如果用户存在应该显示用户，然后用户旁边应该有添加好友按钮
 * 你需要做到点击搜索按钮调用数据库进行查询并显示（如果有用户），点击添加好友将当前用户和目标用户账号传递到
 * UserAction中的addFriend();
 */
public class FindUI extends JFrame implements MouseListener {
    private static String url="jdbc:mysql://localhost:3306/chat";
    private static String user="root";
    private static String passwod="123456";
    //搜索标签
    JLabel jl1 = new JLabel("搜索");
    //搜索框
    public static JTextArea jt = new JTextArea("请输入查询的账号...");
    //搜索按钮
    JButton jb1 = new JButton("搜索");//此处搜索后期用图标代替
    //加好友按钮
    JButton jb2 = new JButton("加好友");
    //昵称标签
    JLabel jl2 = new JLabel();

    WholeUI wholeUI = new WholeUI(this) {
        @Override
        protected void elseWindow(JFrame jFrame) {
            jFrame.setSize(800, 600);
            jFrame.setTitle("搜索");
        }
    };

    public FindUI() {
        //设置搜索标签
        jl1.setBounds(7,7,25,20);
        this.getContentPane().add(jl1);
        //设置搜索框
        jt.setBounds(40,10,700,20);
        this.getContentPane().add(jt);
        //设置搜索按钮
        jb1.setBounds(745,10,35,20);
        jb1.addMouseListener(this);
        this.getContentPane().add(jb1);
    }

    public void query(String username) throws SQLException, ClassNotFoundException {
        Class.forName("com.mysql.cj.jdbc.Driver");
        //连接到数据库，并查询所有username
        Connection c = DriverManager.getConnection(url, user, passwod);
        Statement s = c.createStatement();
        System.out.println("连接到数据库");
        String sql = "select * from user";
        ResultSet r = s.executeQuery(sql);

        int flag = 0;
        while(r.next()){
            String u = r.getString(1);
            if(username.equals(u)){
                System.out.println(r.getString(1));
                //设置昵称
                jl2.setText( "账号: "+u);
                jl2.setBounds(30,55,200,30);
                this.getContentPane().add(jl2);
                this.validate();
                this.repaint();
                //设置加好友按钮
                jb2.setBounds(680,50,90,40);
                jb2.addMouseListener(this);
                this.getContentPane().add(jb2);
                this.validate();
                this.repaint();
                flag = 1;
                break;
            }
        }

        r.close();
        s.close();
        s.close();

        if(flag == 0){
            System.out.println("没有此用户");
            FindUI f = new FindUI();
            //wholeUI.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
            this.dispose();
        }
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        //搜索
        if(e.getSource() == jb1){
            String username = FindUI.jt.getText();
            try {
                query(username);
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            } catch (ClassNotFoundException ex) {
                throw new RuntimeException(ex);
            }
        } else if (e.getSource() == jb2) {//加好友
            new Thread(){AddFriendUI addf = new AddFriendUI();};

            this.dispose();
            //把当前用户和目标用户账号传递到UserAction中的addFriend();
            try {
                System.out.println("当前用户："+LoginUI.currentUser.getUsername()+",正在执行操作");
                String localUsername= LoginUI.currentUser.getUsername();
                String goalUsername= FindUI.jt.getText();
                //获取文件名
                String localFilename= "documents/FriendList/"+localUsername+".txt";
                String goalFilename= "documents/FriendList/"+goalUsername+".txt";
                // 读取本地用户的好友列表
                Set<String> localFriends = readFriendsFromFile(localFilename);
                // 读取目标用户的好友列表
                Set<String> goalFriends = readFriendsFromFile(goalFilename);



                //如果好友不在列表中就添加，在就不添加
                if (!localFriends.contains(goalUsername)){
                    //添加目标用户到本地用户的好友列表
                    appendFriendToFile(localFilename,goalUsername);
                }
                if (!goalFriends.contains(localUsername)){
                    //添加本地用户到目标用户的好友列表
                    appendFriendToFile(goalFilename,localUsername);
                }
                System.out.println("添加好友成功");
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }

    }

    private void appendFriendToFile(String filename, String friend) throws IOException {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filename,true))) {
            writer.write(friend);
            writer.newLine();
        }
    }

    //读取好友列表
    private Set<String> readFriendsFromFile(String filename) throws IOException {
        Set<String> friends = new HashSet<>();
        File file = new File(filename);
        if (file.exists()) {
            try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    friends.add(line.trim());
                }
            }
        }
        return friends;
    }

    @Override
    public void mousePressed(MouseEvent e) {

    }

    @Override
    public void mouseReleased(MouseEvent e) {

    }

    @Override
    public void mouseEntered(MouseEvent e) {

    }

    @Override
    public void mouseExited(MouseEvent e) {

    }
}
